package com.bf.hotpoint.repository.redis;

import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Repository;

import com.bf.hotpoint.domain.TestObject;

@Repository
public class TestRedis {
	// inject the actual template
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

    // inject the template as ListOperations
    // can also inject as Value, Set, ZSet, and HashOperations
    @Resource(name="redisTemplate")
    private ListOperations<String, String> listOps;
    
    @Resource(name="redisTemplate")
    private SetOperations<String, TestObject> setOps;
    
    @Resource(name="redisTemplate")
    private HashOperations<String, String, TestObject> hashOps;

    public void addLink(String name) {
        listOps.leftPush("testList", name);
        // or use template directly
        redisTemplate.boundListOps("testList").leftPush(name);
    }
    
    public void addTestObjectToHash(String id, TestObject testObject) {
        hashOps.put("testMap", id, testObject);
        // or use template directly
        TestObject result = hashOps.get("testMap",id);
        System.out.println(result);
    }
    
    public void setValue(){
    	redisTemplate.opsForValue().set("foo", "bar");
    	redisTemplate.opsForValue().get("foo");
    }
    
    public void addTestObjectToSet(TestObject testObject) {
        setOps.add("testSet", testObject);
        // or use template directly
        Set<TestObject> result = setOps.members("testSet");
        System.out.println(result.size());
    }
    
    public void useCallback() {

    	  redisTemplate.execute(new RedisCallback<Object>() {
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				Long size = connection.dbSize();
			      // Can cast to StringRedisConnection if using a StringRedisTemplate
			      ((StringRedisConnection)connection).set("key", "value");
				return null;
			}
    	   });
    	}
}
